<template>
  <div class="home">
    <router-view @doShow="doShow" v-slot="{ Component }">
      <keep-alive :include="cachedViews">
        <component :is="Component" />
      </keep-alive>
    </router-view>
    <!-- <router-view @doShow="doShow" /> -->
    <van-tabbar v-model="activeName" fixed route v-if="isTabbar && showFlag">
      <van-tabbar-item v-for="tabbarItem in tabbarList" :key="tabbarItem.id" :to="tabbarItem.to"
        :name="tabbarItem.name">
        <template #icon="props">
          <img :src="tabbarItem.name == activeName ? tabbarItem.icon.active : tabbarItem.icon.inactive" />
        </template>
        {{ tabbarItem.title }}
      </van-tabbar-item>
    </van-tabbar>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, watch, onUnmounted } from "vue";
import { TABBAR_LIST } from "@/constant/enums";
import { useRouter } from "vue-router";
const router = useRouter();
const cachedViews = ref<any>([]);
const isTabbar = ref<any>(false)

const activeName = ref("home");
watch(() => router.currentRoute.value, (v) => {

  // 获取所有缓存路由
  if (v.meta.keepAlive) {
    if (!cachedViews.value.includes(v.name)) {
      cachedViews.value.push(v.name);
    }
  } else {
    // nocache 解决子路由返回父路由后再次访问子路由时，子路由仍然被缓存的情况
    if (v.meta.nocache) {
      cachedViews.value = []
    }
  }
  isTabbar.value = v?.meta?.isTabbar

  //默认tab img判断
  const routerName: any = router.currentRoute.value.name
  if (routerName == 'Index') {
    activeName.value = 'home'
  } else if (routerName == 'productList') {
    activeName.value = 'productList'
  } else if (routerName == 'supplierList') {
    activeName.value = 'supplierList'
  } else if (routerName == 'Profile') {
    activeName.value = 'Profile'
  }
}, { immediate: true });


const showFlag = ref<Boolean>(true)
const bottomIsShow = ref(true)
const defaultPhoneHeight = ref(0) //屏幕默认高度
const nowPhoneHeight = ref(0) //屏幕现在的高度
// 在组件挂载完成后添加事件监听器
onMounted(() => {
  defaultPhoneHeight.value = window.innerHeight;
  // 添加事件监听器
  window.addEventListener('resize', handleResize);
})
// 处理窗口大小变化的函数
const handleResize = () => {
  nowPhoneHeight.value = window.innerHeight;
};
// 在组件卸载前移除事件监听器
onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
});

watch(nowPhoneHeight, () => {
  if (defaultPhoneHeight.value != nowPhoneHeight.value) {
    // 当软键盘弹出,改变bottomIsSHow变量然后去控制bottom的显示与隐藏
    bottomIsShow.value = false;
  } else {
    // 相等代表软键盘收起后,与上同理
    bottomIsShow.value = true
  }
})

const doShow = (val: Boolean) => {
  showFlag.value = val
}


const tabbarList = TABBAR_LIST;
</script>

<style lang="less" scoped>
.home {
  // padding-bottom: 50px;
  // min-height: 100vh;
  background: @default-bg-color;
  box-sizing: border-box;
  overflow: hidden
}

:deep(.van-tabbar) {
  height: 50px !important;
}

.van-tabbar-item__icon img {
  height: 25px;
  transform: translateX(2px);
}
</style>
